<template>
  <div>
    <NoAuthPage v-showNoAuth="'E11-1'" :imgBoxStyle="{height:'40vh',margin:'0 10px 10px'}"/>

    <a-row style="margin:10px 0 20px" v-userAuth="'E11-1'">
      <a-col :span="$store.state.language=='zh'?4:24">
        <!-- <a-button type="primary" @click="backup_rule_dialog = true" style="margin-right:10px">{{$t('Set-backup-rules')}}</a-button> -->
        <a-button v-userAuth="'E11-2'" type="primary" @click="download_dialog = true">
          <!-- <i class="icon icon-download16f button-icon-style"></i> -->
          
          <Iconfont class="icon button-icon-style" type="icon-download16f"></Iconfont>
          {{$t('Download')}}
        </a-button>
      </a-col>
      <a-col :span="$store.state.language=='zh'?20:24" :style="$store.state.language=='zh'?{}:{margin:'5px 0'}">
        <div class="filter-box">
          <span>
            {{$t('Level')}}：
            <a-radio-group v-model="levelValue" button-style="solid" @change="changeLevel">
              <a-radio-button v-for="(item,index) in level_radios" :value="item.value" :key="index">{{item.name}}</a-radio-button>
            </a-radio-group>
          </span>
          <span>
            {{$t('Event-status')}}：
            <a-radio-group v-model="eventValue" button-style="solid" @change="changeEventStatus">
              <a-radio-button v-for="(item,index) in event_radios" :value="item.value" :key="index">{{item.name}}</a-radio-button>
            </a-radio-group>
          </span>
          <div style="line-height:32px">{{$t('Time-frame')}}：</div>
          <div>
            <a-range-picker v-model="timeRangeModel"
                            :placeholder="[$t('Start-date'), $t('End-date')]"
                            @ok="handleFilterTime"
                            @change="handleClearTime"
                            :show-time="{ format: 'HH:mm' }"
                            format="YYYY-MM-DD HH:mm"
                            :locale="rangePickerLocal"
                            style="width:100%" ></a-range-picker>
                            <!-- @change="changeCheckTime" -->
          </div>
        </div>
      </a-col>
    </a-row>
    <!--表格-->
    <div class="check-table" v-userAuth="'E11-1'">
      <a-table :columns="columns" :dataSource="tableData" :loading="tableLoading" size="small" 
                bordered :pagination='pagination' rowKey="id" :locale="defaultSetting"
                :scroll="screenPixel>=1920?{}:{ x: 1300 }">
        <template slot="operator" slot-scope="text, record">
          <span v-if="text">{{text}}</span>
          <span v-else>-</span>
        </template>
        <template slot="level" slot-scope="text, record">
          <div v-if="text == 3">
            <span class="red-circle"></span><span>{{$t('High')}}</span>
          </div>
          <div v-else-if="text == 2">
            <span class="orange-circle"></span><span>{{$t('Middle')}}</span>
          </div>
          <div v-else-if="text == 1">
            <span class="blue-circle"></span><span>{{$t('Low')}}</span>
          </div>
        </template>
        <template slot="event_status" slot-scope="text, record">
          <div v-if="text == 0">
            <span class="green-circle"></span><span>{{$t('Success')}}</span>
          </div>
          <div v-else-if="text == 1">
            <span class="red-circle"></span><span>{{$t('Fail')}}</span>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record">
          <!-- <span class="detail-text" @click="showDetail(record)">{{$t('Detail')}}</span> -->
            <a-tooltip placement="top">
              <template slot="title">
                {{$t('Detail')}}
              </template>
              <!-- <i class="icon icon-catalogue16f table-operation-icon" @click="showDetail(record)"></i> -->

          <Iconfont class="icon table-operation-icon" type="icon-catalogue16f" @click="showDetail(record)"></Iconfont>
            </a-tooltip>
        </template>
      </a-table>
    </div>

    <!--备份规则 已去掉-->
    <!-- <BackupRule
      v-if="backup_rule_dialog"
      :visible="backup_rule_dialog"
      @closeDrawer="closeBackUpRuleDrawer"
    /> -->

    <!--下载日志-->
    <DownloadLog 
        v-if="download_dialog"
        :visible="download_dialog" 
        @closeDialog="closeDialog"
    />

    <!--日志详情-->
    <!-- <div v-if="detail_dialog"> -->
    <a-modal
      :title="$t('Log-details')"
      :visible="detail_dialog"
      width='40%'
      @cancel="handleCancelLog" :maskClosable='false'
      v-dragModal
    >
      <a-descriptions
        bordered 
        size="small"
        :column="4"
      >
        <a-descriptions-item v-for="(item,index) in logDetails" 
                             :label="$store.state.language=='zh'?item.title_ch:item.title_en"
                             :span="item.span" :key="index">
          <div v-if="index!=2 && index!=3">{{item.value}}</div>
          <!--级别-->
          <div v-else-if="index == 2">
            <template v-if="item.value == 3"><!--高-->
              <span class="red-circle"></span>{{$t('High')}}
            </template>
            <template v-else-if="item.value == 2"><!--中-->
              <span class="orange-circle"></span>{{$t('Middle')}}
            </template>
            <template v-else-if="item.value == 1"><!--低-->
              <span class="blue-circle"></span>{{$t('Low')}}
            </template>
          </div>
          <!--事件状态-->
          <div v-else-if="index == 3">
            <template v-if="item.value == 0">
              <span class="green-circle"></span>{{$t('Success')}}
            </template>
            <template v-else-if="item.value == 1">
              <span class="red-circle"></span>{{$t('Fail')}}
            </template>
          </div>
        </a-descriptions-item>
      </a-descriptions>
      <template slot="footer">
        <a-button key="submit" type="primary" @click="handleCancelLog">{{$t('Sure')}}</a-button>
      </template>
    </a-modal>
    <!-- </div> -->
  </div>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
// import BackupRule from '@/views/operation/log_manage/subpage/operateLogOper/BackupRule'
import DownloadLog from '@/views/operation/log_manage/subpage/operateLogOper/DownloadLog'
import NoAuthPage from '@/components/common/NoAuthPage'

import { getTimestampFromString } from '@/untils/formatTime'
import request from '@/request/request'

export default {
  name: "OperateLog",
  components: { EmptyData, DownloadLog, NoAuthPage },//BackupRule
  data() {
    return {
      backup_rule_dialog: false,
      download_dialog: false,
      detail_dialog: false,
      levelValue: 4,
      level_radios: [
        {name:this.$t('All'),value:4},
        {name:this.$t('High'),value:3},
        {name:this.$t('Middle'),value:2},
        {name:this.$t('Low'),value:1}
      ],
      eventValue: 2,
      event_radios: [
        {name:this.$t('All'),value:2},
        {name:this.$t('Success'),value:0},
        {name:this.$t('Fail'),value:1},
      ],
      timeRangeModel: null,
      timeRange: ['', ''],
      rangePickerLocal: {
        "lang": {
          "placeholder": "Select date",
          "rangePlaceholder": ["Start date", "End date"],
          "today": "Today",
          "now": "Now",
          "backToToday": "Back to today",
          "ok": this.$t('Sure'),
          "clear": "Clear",
          "month": "Month",
          "year": "Year",
          "timeSelect": this.$t('Select-time-picker'),
          "dateSelect": this.$t('Select-date-picker'),
          "monthSelect": "Choose a month",
          "yearSelect": "Choose a year",
          "decadeSelect": "Choose a decade",
          "yearFormat": "YYYY",
          "dateFormat": "M/D/YYYY",
          "dayFormat": "D",
          "dateTimeFormat": "M/D/YYYY HH:mm:ss",
          "monthFormat": "MMMM",
          "monthBeforeYear": true,
          "previousMonth": "Previous month (PageUp)",
          "nextMonth": "Next month (PageDown)",
          "previousYear": "Last year (Control + left)",
          "nextYear": "Next year (Control + right)",
          "previousDecade": "Last decade",
          "nextDecade": "Next decade",
          "previousCentury": "Last century",
          "nextCentury": "Next century"
        },
      },
      columns: [
        { title: this.$t('Attribute-date'), dataIndex: 'data', key: 'data',width:120,ellipsis: true, },
        { title: this.$t('Level'), dataIndex: 'level', key: 'level',scopedSlots:{customRender:'level'},width:100,ellipsis: true, },
        { title: this.$t('Event-status'), dataIndex: 'status', key: 'status',scopedSlots:{customRender:'event_status'},width:100,ellipsis: true, },
        { title: this.$t('Operator'), dataIndex: 'operator', key: 'operator',width:120,ellipsis: true, scopedSlots:{customRender:'operator'},},
        { title: this.$t('Occurrence-node'), dataIndex: 'happen_node', key: 'happen_node',width:150,ellipsis: true, },
        // { title: this.$t('Storage-location'), dataIndex: 'position', key: 'position',width:150,ellipsis: true, },
        { title: this.$t('Event-type'), dataIndex: 'event_type', key: 'event_type',width:100,ellipsis: true, },
        { title: this.$t('Event-object'), dataIndex: 'objname', key: 'objname',width:150,ellipsis: true, },
        { title: this.$t('Event-occur-time'), dataIndex: 'begin_time', key: 'begin_time',width:170,ellipsis: true, },
        { title: this.$t('Event-end-time'), dataIndex: 'end_time', key: 'end_time',width:170,ellipsis: true, },
        { title: this.$t('Operate'), dataIndex: 'oper', key: 'oper',scopedSlots:{customRender:'operation'},width:100,ellipsis: true, fixed: 'right',},
      ],
      pagination:{
	      defaultPageSize:10,
        total: 0,
	      showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
	      showSizeChanger:true,
	      pageSizeOptions: ['10', '15', '20'],
        onChange: (page, pageSize) => this.pageChange(page, pageSize),
	      onShowSizeChange: (current, pageSize) => this.pageSizeChange(current, pageSize),
				buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
      },
      defaultSetting: {emptyText:<EmptyData />},
      tableLoading: false,
      tableData: [],
      tableData_copy: [],
      targetLog: {},
      logDetails: [
        {title_ch:'日期：', title_en:'Date:', value:undefined, span:2 },
        {title_ch:'操作人：', title_en:'Operator:', value:undefined, span:2 },
        {title_ch:'级别：', title_en:'Level:', value:undefined, span:2 },
        {title_ch:'事件状态：', title_en:'Event status:', value:undefined, span:2 },
        {title_ch:'产生时间：', title_en:'Generation time:', value:undefined, span:2 },
        {title_ch:'结束时间：', title_en:'End time:', value:undefined, span:2 },
        // {title_ch:'存储位置：', title_en:'Storage location:', value:'日期', span:3 },
        {title_ch:'事件类型：', title_en:'Event type:', value:undefined, span:2 },
        {title_ch:'产生节点：', title_en:'Generation node:', value:undefined, span:2 },
        {title_ch:'事件对象详情：', title_en:'Event object details:', value:undefined, span:3 },
      ],
      currentPage: 1,
      pageSize: 10,
      screenPixel: window.screen.width //window.screen.width * window.devicePixelRatio
    }
  },
  mounted() {
    this.getOperateLogData(this.currentPage, this.pageSize);
    if(this.screenPixel>=1920) {
      this.columns[this.columns.length-1].fixed = '';
    }else {
      this.columns[this.columns.length-1].fixed = 'right';
    }
  },
  watch: {
    getlanguage() {
      this.rangePickerLocal = {
        "lang": {
          "placeholder": "Select date",
          "rangePlaceholder": ["Start date", "End date"],
          "today": "Today",
          "now": "Now",
          "backToToday": "Back to today",
          "ok": this.$t('Sure'),
          "clear": "Clear",
          "month": "Month",
          "year": "Year",
          "timeSelect": this.$t('Select-time-picker'),
          "dateSelect": this.$t('Select-date-picker'),
          "monthSelect": "Choose a month",
          "yearSelect": "Choose a year",
          "decadeSelect": "Choose a decade",
          "yearFormat": "YYYY",
          "dateFormat": "M/D/YYYY",
          "dayFormat": "D",
          "dateTimeFormat": "M/D/YYYY HH:mm:ss",
          "monthFormat": "MMMM",
          "monthBeforeYear": true,
          "previousMonth": "Previous month (PageUp)",
          "nextMonth": "Next month (PageDown)",
          "previousYear": "Last year (Control + left)",
          "nextYear": "Next year (Control + right)",
          "previousDecade": "Last decade",
          "nextDecade": "Next decade",
          "previousCentury": "Last century",
          "nextCentury": "Next century"
        }
      };
      this.columns = [
        { title: this.$t('Attribute-date'), dataIndex: 'data', key: 'data',width:120,ellipsis: true, },
        { title: this.$t('Level'), dataIndex: 'level', key: 'level',scopedSlots:{customRender:'level'},width:100,ellipsis: true, },
        { title: this.$t('Event-status'), dataIndex: 'status', key: 'status',scopedSlots:{customRender:'event_status'},width:100,ellipsis: true, },
        { title: this.$t('Operator'), dataIndex: 'operator', key: 'operator',width:120,ellipsis: true, scopedSlots:{customRender:'operator'},},
        { title: this.$t('Occurrence-node'), dataIndex: 'happen_node', key: 'happen_node',width:150,ellipsis: true, },
        // { title: this.$t('Storage-location'), dataIndex: 'position', key: 'position',width:150,ellipsis: true, },
        { title: this.$t('Event-type'), dataIndex: 'event_type', key: 'event_type',width:100,ellipsis: true, },
        { title: this.$t('Event-object'), dataIndex: 'objname', key: 'objname',width:150,ellipsis: true, },
        { title: this.$t('Event-occur-time'), dataIndex: 'begin_time', key: 'begin_time',width:170,ellipsis: true, },
        { title: this.$t('Event-end-time'), dataIndex: 'end_time', key: 'end_time',width:170,ellipsis: true, },
        { title: this.$t('Operate'), dataIndex: 'oper', key: 'oper',scopedSlots:{customRender:'operation'},width:100,ellipsis: true, fixed: 'right',},
      ];
      this.level_radios = [
        {name:this.$t('All'),value:4},
        {name:this.$t('High'),value:3},
        {name:this.$t('Middle'),value:2},
        {name:this.$t('Low'),value:1}
      ];
      this.event_radios = [
        {name:this.$t('All'),value:2},
        {name:this.$t('Success'),value:0},
        {name:this.$t('Fail'),value:1},
      ];
    },
  },
  computed: {
    getlanguage(){
			return this.$store.state.language
		},
  },
  methods: {
    //获取操作日志
    getOperateLogData(page, pageSize) {
      this.tableLoading = true;
      request('post', 'logmanage/pentalog/record',{
        level: this.levelValue, //时间等级（1低，2中，3高，4全部）
        status: this.eventValue, //事件状态（0成功，1失败，2全部）
        head: (page-1)*pageSize, //分页开始的记录
        end: pageSize*page - 1, //分页结束的记录
        begin_time: this.timeRange[0], //开始时间
        end_time: this.timeRange[1] //结束时间
      }).then(res => {
        // console.log('获取操作日志', res)
        if(res.data.success) {
          this.tableData = res.data.result;
          this.pagination.total = res.data.count;
        }
      }).catch(err => {
        console.log(err);
      }).finally(() => {
        this.tableLoading = false;
      })
    },

    //页码改变
    pageChange(currentPage, pageSize) {
      this.currentPage = currentPage;
      this.pageSize = pageSize;
      this.getOperateLogData(this.currentPage, this.pageSize);
    },

    //每页大小改变
    pageSizeChange(currentPage, pageSize) {
      this.currentPage = currentPage;
      this.pageSize = pageSize;
      this.getOperateLogData(this.currentPage, this.pageSize);
    },

    //显示详情
    showDetail(record) {
      this.targetLog = record;
      this.detail_dialog = true;
      this.logDetails[0].value = record.data; //日期
      this.logDetails[1].value = record.operator?record.operator:'-'; //操作人
      this.logDetails[2].value = record.level; //级别
      this.logDetails[3].value = record.status; //事件状态
      this.logDetails[4].value = record.begin_time; //产生时间
      this.logDetails[5].value = record.end_time; //结束时间
      // this.logDetails[6].value = record.; //存储位置
      this.logDetails[6].value = record.event_type; //事件类型
      this.logDetails[7].value = record.happen_node; //产生节点
      this.logDetails[8].value = record.objname; //事件对象详情
    },
    //取消显示详情
    handleCancelLog() {
      this.detail_dialog = false;
    },

    //筛选方法
    filterTableMethod() {
      //eventValue
      //levelValue
      //timeRange
      let finalData = this.tableData_copy;
      if(this.levelValue == 'all' && this.eventValue == 'all' && this.timeRange.length == 0) {
        this.tableData = this.tableData_copy;
      }
      if(this.levelValue != 'all') {
        finalData = finalData.filter(item => {
          return item.级别 == this.levelValue;
        })
      }
      if(this.eventValue != 'all') {
        finalData = finalData.filter(item => {
          return item.事件状态 == this.eventValue;
        })
      }
      if(this.timeRange.length != 0) {
        finalData = finalData.filter(item => {
          // 将时间字符串'2022-07-22 13:45:44'转为时间戳
          let create_time = getTimestampFromString(item.产生时间) / 1000;
          return create_time <= this.timeRange[1] && create_time >= this.timeRange[0];
        })
      }
      this.tableData = finalData;
    },

    //筛选级别
    changeLevel() {
      this.getOperateLogData(this.currentPage, this.pageSize);
    },

    //筛选事件状态
    changeEventStatus() {
      this.getOperateLogData(this.currentPage, this.pageSize);
    },

    //筛选时间
    handleFilterTime() {
      this.getOperateLogData(this.currentPage, this.pageSize);
    },
    //解决清空时间
    handleClearTime(value, dateString) {
      this.timeRange[0] = dateString[0]
      this.timeRange[1] = dateString[1]
      if(value.length == 0) {
        this.getOperateLogData(this.currentPage, this.pageSize);
      }
    },

    //关闭备份规则抽屉
    closeBackUpRuleDrawer() {
      this.backup_rule_dialog = false;
    },

    //关闭下载弹窗
    closeDialog() {
      this.download_dialog = false;
    },
  },
}
</script>
<style scoped>
  .filter-box {
    display: flex;
    justify-content: flex-end;
  }
  .filter-box span {
    line-height: 32px;
    margin-right: 20px;
  }
  .detail-text {
    color: var(--themeColor);
    cursor: pointer;
  }
  ::v-deep.ant-descriptions-bordered.ant-descriptions-small .ant-descriptions-item-label, 
  ::v-deep.ant-descriptions-bordered.ant-descriptions-small .ant-descriptions-item-content {
    padding: 9px;
  }
</style>